if (typeof Ext == "undefined")
{
	Ext = {};
	Ext.namespace = function()
	{
	    var a = arguments, o = null, i, j, d, rt;
	    for (i = 0,ilen=a.length; i < ilen; ++i) 
	    {
	        d = a[i].split(".");
	        rt = d[0];
	        eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
	        for (j = 1,jlen=d.length; j < jlen; ++j) 
	        {
	            o[d[j]] = o[d[j]] ||
	            {};
	            o = o[d[j]];
	        }
	    }
	}
}
Ext.namespace("Milan.UsbKey");
Milan.UsbKey.DEFAULT_USBKEY_LOGIN_OCX_ID = "usbKeyLoginOCX";
Milan.UsbKey.DEFAULT_STAMP_OCX_ID        = "stampObjId";
/**
 * 往网页中初始化usbkey控件,返回值: 失败=null 成功=login控件,不建议直接使用返回的控件，没有必要。
 * @param {} targetId
 * @param {} ocxId
 * @param {} cab
 * @param {} classid
 * @return {Boolean}
 */
Milan.UsbKey.initUsbKeyOCX = function(targetId,ocxId,cab,classId)
{	
	if (navigator.appName.indexOf("Microsoft") == -1) 
	{
		return false;
	}
	ocxId = ocxId || Milan.UsbKey.DEFAULT_USBKEY_LOGIN_OCX_ID;
	var result = Milan.UsbKey.getUsbKeyOCX(ocxId);
	if (!result)
	{
		cab = cab || "/cab/ntkosigntoolv3.cab#version=3,0,2,0";
		classId = classId|| "clsid:97D0031E-4C58-4bc7-A9BA-872D5D572896";
		var html = '<object id="'+ocxId+'" classid="'+classId+'" codebase="'+cab+'" width=0 height=0><param name="IsUseUTF8Data" value="-1"><param name="IsUseUTF8URL" value="-1"><param name="ProductCaption" value="三五互联"><param name="ProductKey" value="BB43D3BB322104FD217C787C791CE19CBBE56AE0"></object>';
		if(targetId){
			var span = document.createElement("SPAN");
			span.innerHTML = html;
			document.getElementById(targetId).appendChild(span);
		}else{
			if (typeof jQuery != "undefined") {
				jQuery("body").append(html);
			}else{
				$("body").append(html);
			}
		}
		return Milan.UsbKey.getUsbKeyOCX(ocxId);
	}
	else
		return result;
	
}
/*往网页中初始化login控件
 *返回值: 失败=null 成功=login控件
 *不建议直接使用返回的控件，没有必要。
 */
Milan.UsbKey.initUsbKeyToolOCX = function(ocxId)
{	
	ocxId = ocxId || Milan.UsbKey.DEFAULT_USBKEY_LOGIN_OCX_ID;
	var cab = "/cab/ntkosigntoolv3.cab#version=3,0,2,0";
	var classId = "clsid:97D0031E-4C58-4bc7-A9BA-872D5D572896";
	return Milan.UsbKey.initUsbKeyOCX("",ocxId ,cab,classId);
}
/*
 * 获取网页上存在的usbkey控件,返回null时为失败
 */
Milan.UsbKey.getUsbKeyOCX = function(ocxId)
{
	var ocxId = ocxId || Milan.UsbKey.DEFAULT_USBKEY_LOGIN_OCX_ID;
	if (!document.all[ocxId] || typeof document.all[ocxId].StatusCode == "undefined")
		return null;
	else
		return document.all[ocxId];
}
/*
 * 判断key是否有插入
 */
Milan.UsbKey.isInsertUsbKey = function(){
	var key = Milan.UsbKey.initUsbKeyToolOCX();
	if(key && key.IsEkeyConnected){
		return true;
	}
	return false;
}
/*
 * 从UsbKey中读取登录信息，此函数会自动尝试初始化登录控件
 * 参数:_options={
 * 			notifyBrowerError:true,		//是否提示浏览器错误
			notifyInitOCXError:true		//是否提示控件初始化错误
 * }
 * 
 * 成功时返回值为对象，结构如下:
 * {
 * 	userName	用户名(目前为绑定时存入的加密信息)W
 * 	keyId		KeyId
 * }
 * 出错返回值:
 * -1:初始化控件失败
 * -2:从key中读取信息时错误，也可能是没插KEY
 * -3:IE only
 */
Milan.UsbKey.readLoginInfoFromUsbKey = function(_options)
{
	if (!_options) _options={
			notifyBrowerError:true,
			notifyInitOCXError:true
	};
	
	if (navigator.appName.indexOf("Microsoft") == -1) 
	{
		if (_options.notifyBrowerError)
			notify("USBKey功能目前只支持IE浏览器,请更换浏览器！");
		return -3;
	}
	var ocx=  Milan.UsbKey.initUsbKeyToolOCX();
	if (!ocx) 
	{
		if (_options.notifyInitOCXError)
			notify("无法初始化USBKey登录控件，请确认浏览器或安全软件是否禁用了USBKey登录控件！");
		return -1;
	}	
	try
	{
		if(!ocx.IsEkeyConnected){
			return -2;
		}
		ocx.GetEkeyUser();
		if(0 != ocx.StatusCode){
			return {keyId:ocx.EkeySN,userName:""};
		}
	}
	catch(e)
	{
		return -2;
	}
	var result = {
			userName : ocx.GetEkeyUser(),
			keyId	: ocx.EkeySN
	}
	return result;
	
	function notify(msg,title)
	{
		var _title = title || '提示信息';
		if (Milan.commonutils)
			Milan.commonutils.createDelayNotifyModel(title,msg);
		else
			alert(msg);
	}
	
}



/*
 * 将登录信息写入UsbKey中，此函数会自动尝试初始化登录控件
 * 参数r结构如下:
 * {
 * 	userName	用户名(目前为绑定时存入的加密信息)W
 * 	userPwd		用户密码(目前没有使用)
 * 	keyId		KeyId
 * }
 * 出错返回值:
 * -1:初始化控件失败
 * -2:从key中读取信息时错误，也可能是没插KEY
 * -3:IE only
 */
Milan.UsbKey.saveLoginInfoToUsbKey = function(r)
{
	if (navigator.appName.indexOf("Microsoft") == -1) 
	{
		return -3;
	}
	var ocx=  Milan.UsbKey.initUsbKeyToolOCX();
	if (!ocx) 
	{
		return -1;
	}	
	try
	{
		ocx.SetEkeyUser(r.userName);
	}
	catch(e)
	{
		return -2;
	}
	var result = {
			userName : r.userName,
			keyId	: ocx.EkeySN
	}
	return result;
}
//签章控件的id
Milan.UsbKey.DEFAULT_USBKEY_WEBSIGN_OCX_ID = "usbKeyWebSignOCX";
/**
 * 初始化印章控件
 * @param {} ocxId
 * @param {} targetId//存放object标签的容器id
 */
Milan.UsbKey.initUsbKeyWebSignOCX = function(targetId,ocxId){
	ocxId = ocxId || Milan.UsbKey.DEFAULT_USBKEY_WEBSIGN_OCX_ID;
	var cab = "cab/ntkoWebSign.cab#version=4,0,2,2";
	var classId = "clsid:DB5B521C-DA92-48e0-AE32-BDC944858D42";
	return Milan.UsbKey.initUsbKeyOCX(targetId,ocxId ,cab,classId);
};
/**
 * 验证印章控件是否有效
 */
Milan.UsbKey._validateWebSignUsbKey = function(targetId,validate,encryptUserName){
	if (navigator.appName.indexOf("Microsoft") == -1) 
	{
		Milan.commonutils.createDelayNotifyModel('提示信息',"USBKey功能目前只支持IE浏览器,请更换浏览器！");
		return false;
	}
	var key = Milan.UsbKey.initUsbKeyWebSignOCX(targetId,targetId+"_ocxId");
	if(!key){
		Milan.commonutils.createDelayNotifyModel('提示信息',"无法初始化USBKey控件，请确认是否已插入USBKey，或者浏览器或安全软件是否禁用了USBKey控件！");
		return false;
	}
	if(validate){
		if(!key.IsEkeyConnected){
			Milan.commonutils.createDelayNotifyModel('提示信息',"请确定已<a href='/desktop/HaiKeyCSP驱动.zip' style='color:red'>安装驱动</a>！或者确认已插入USBKey！或者重新拔插下USBKey！");
			return false;
		}
		var loginKey = Milan.UsbKey.readLoginInfoFromUsbKey();
		if(!loginKey || !loginKey.userName){
			return false;		
		}
		if(!encryptUserName){
			var belong = true;
			jQuery.ajax('archiveTransAction.do?actionType=54&usbkey='+key.EkeySN,
				{dataType:"html",
				 async:false,//此处需要使用同步调用，否则未判断进行下面判断，这个function就返回了。。
				 success:function(data){
					if(!data || data != loginKey.userName){
							Milan.commonutils.createDelayNotifyModel('提示信息',"插入的USBKey控件，不属于该用户！请插入该用户对应的USBKey。");
							belong = false;
					}
				 }
			});
			if(!belong)return false;
		}else if(encryptUserName!=loginKey.userName){
			Milan.commonutils.createDelayNotifyModel('提示信息',"插入的USBKey控件，不属于该用户！请插入该用户对应的USBKey。");
			return false;
		}
	}
	return key;
};
/**
 * 印章方法
 * @param {} webSignInfo
 * @param {} tagId
 * @param {} encryptUserName
 * @param {} ocxId
 */
Milan.UsbKey.AddSecSignFromUSBKEY = function(formId,webSignInfo,tagId){
	jQuery("#dialogDiv").find(".top_pop_tip").remove();//清除头部的提示信息
	var key = Milan.UsbKey._validateWebSignUsbKey(formId,true);
	if(!key){
		return;
	}
	jQuery("#"+formId).find("#"+tagId).parent().attr("id","stampspan_"+tagId);
	var IsCheckDocChange = false;
	key.WebSignFormId = formId;
	var secSignObj = key.AddSecSignOcx("SecSignFromURLID",0,-24);
	secSignObj.WebSignInfo = webSignInfo;
	if(webSignInfo) IsCheckDocChange = true;
	secSignObj.PositionTagId = "stampspan_"+tagId;
    secSignObj.ReSetHTMLPosition();
    secSignObj.UserData = formId + "," +tagId;
    secSignObj.HiddenMenuItems=223;
    secSignObj.IsAllowAddHandSign=false;//设置禁止添加手写签名
	secSignObj.IsAllowAddSignTime=false;//设置禁止添加时间
	secSignObj.IsAllowEditComment=false;//设置禁止添加批注
	key.AddSecSignFromEkey(secSignObj,Milan.currentUserRealName,2,false,true,IsCheckDocChange,false,'',false);
	jQuery("#"+formId).find("#"+tagId).prop("secsign","1");
	if(secSignObj.SignSource){
		jQuery("#"+formId).find("#"+tagId).css("visibility","hidden");
		jQuery("#"+formId).find("input[name='mushSaveStampCount']").val(1);
	}
	jQuery("#"+formId).find("#"+tagId).parent().removeAttr("id");
};

/**
 * 将盖章保存到服务器！config 包括formId,encryptUserName,url,params,callback
 */
Milan.UsbKey.saveStampToServer = function(config){
	config = config||{};
	if(config && config.formId && jQuery("#"+config.formId).find("input[macrotype='stampwidget'][type='button']").length > 0){
		var key = Milan.UsbKey._validateWebSignUsbKey(config.formId,true,config.encryptUserName);
		if(!key){
			return false;
		}
		var buttons = jQuery("#"+config.formId).find("input[macrotype='stampwidget'][type='button']");
		var obj = null;
		var signNames = "&signNames=";
		for(var i=0,len=buttons.length;i<len;i++){
			obj = jQuery(buttons[i]).parent().find("object");
			if(obj && obj[0] && obj[0].classid == "clsid:AA4B3728-B61C-4bcc-AEE7-0AA47D3C0DDA"){
				obj[0].IsMarked = true;
				if(buttons[i].secsign == 1){
					signNames = signNames + obj[0].SignName + ",,,";
				}
			}
		}
		signNames = encodeURI(signNames);
		var params = (config.params).replace(/%/g,"%25").replace(/&/g,"%26")+signNames+"&keyId="+key.EkeySN;
		var result = key.SaveToURL(config.url,"webSignFile",params,"ntkowebsigns.info",config.formId,true);
		var XMLDoc = null;
		if(result.indexOf("<?xml ") == 0){
			XMLDoc = new ActiveXObject("Microsoft.XMLDOM");
            XMLDoc.async = false;
            XMLDoc.loadXML(result); //loadXML方法载入xml字符串
		}
		var response = {};
		response.responseXML = XMLDoc;
		response.responseText = result;
		Milan.ajaxutility.AjaxRequestInteceptor(response,"",config.callback);
		return true;
	}
	return false;
};
Milan.UsbKey.loadStampFromURL = function(formId,fileName,writtableFields){
	if(jQuery("#"+formId).find("input[macrotype='stampwidget'][type='button']").length > 0){
		if(!Milan.navigator.isIE){
			Milan.commonutils.createDelayNotifyModel('提示', '请使用ie浏览器，因为该事务包含印章控件，否则无法正常显示该流程！');
			return;
		}
		var key = Milan.UsbKey._validateWebSignUsbKey(formId,false);
		if(!key){
			return false;
		}
		jQuery("#"+formId).find("input[macrotype='stampwidget'][type='button']").each(function(){
			jQuery(this).parent().attr("id","stampspan_"+this.id);
		});
		try{
			if(fileName){
				var showStamp = function(){
					key.LoadFromURL("downloadAction.do?fileAsName="+fileName);
					jQuery("#"+formId).find("input[macrotype='stampwidget'][type='button']").each(function(){
					jQuery(this).parent().removeAttr("id");
					var obj = jQuery(this).parent().find("object");
					if(obj && obj[0] && obj[0].classid == "clsid:AA4B3728-B61C-4bcc-AEE7-0AA47D3C0DDA"){
						obj = obj[0];
						jQuery(this).css("visibility","hidden");//隐藏印章按钮
						if(obj.UserData && obj.UserData.indexOf(",") > 0){//重新设置UserData，删除事件才能正确触发
							obj.UserData = formId + ","+obj.UserData.substring(obj.UserData.indexOf(",")+1);
						}
						//以下用于隐藏右键功能
						if(writtableFields && writtableFields.indexOf(',' + this.id + ',') >= 0){
							obj.HiddenMenuItems=223;
						}else{
							obj.HiddenMenuItems=255;
						}
						}
					});
				};
				key.WebSignFormId = formId;
				setTimeout(showStamp,10);
			}
		}catch(e){}
		return true;
	}
	return false;
};
//验证方法
Milan.UsbKey.CheckStampStatusAndCallback=function(formId,callback){
	var msg = '';
	jQuery("#"+formId).find("input[macrotype='stampwidget'][type='button']").each(function(){
		var obj = jQuery(this).parent().find("object");
		if(obj && obj[0] && obj[0].classid == "clsid:AA4B3728-B61C-4bcc-AEE7-0AA47D3C0DDA"){
			obj = obj[0];
			if(obj.WebSignInfo){
				obj.CheckDocChange(true);
				obj.RefreshCheckStatus();
				if(!obj.IsSignChecked){
					msg = '印章 <span style="color:red">'+obj.SignName+'</span> 验证错误，其保护字段已被修改！确定要提交吗？';
					return;
				}
			}else{
				obj.CheckDocChange(false);
			}
		}
	});
	if(msg){
		new Milan.widget.ConfirmDialog("确认",msg,{confirmCallback : callback});
	}else{
		callback();
	}
};
/**
 * 删除签章后的事件，是签章控件内部调用。
 * @param {} UserName
 * @param {} SignName
 * @param {} SignUser
 * @param {} SignSN
 * @param {} EkeySN
 * @param {} UserData
 */
function NtkoReservedEvent_AfterSecSignDeleted(UserName,SignName,SignUser,SignSN,EkeySN,UserData){
	if(UserData && UserData.indexOf(",")>0){
		var data = UserData.split(",");
		jQuery("#"+data[0]).find("#"+data[1]).css("visibility","visible");
		jQuery("#"+data[0]).find("input[name='mushSaveStampCount']").val(1);
	}else{
		jQuery("#"+UserData).css("visibility","visible");
	}
}
//注意:这是内部需要使用的函数，除
//ocxElement.codebase = "ntkoWebSign.cab#version=4,0,2,2";
//语句可以根据需要修改之外，其他语句不要修改
function NtkoReserved_AddSecSignOcx(ControlID,ocxLeft,ocxTop)
{
	var ocxElement = null;
	try
	{
		ocxElement = document.createElement('object');
		if("string" == typeof(ControlID))
		{
			ocxElement.id = ControlID;
		}
		ocxElement.style.position = "absolute";
		ocxElement.style.pixelLeft = ocxLeft;
		ocxElement.style.pixelTop = ocxTop;
		ocxElement.codebase = "cab/ntkoWebSign.cab#version=4,0,2,2";
		ocxElement.classid = "clsid:AA4B3728-B61C-4bcc-AEE7-0AA47D3C0DDA"; 
		ocxElement.width = "10";
		ocxElement.height = "10";
		document.body.appendChild(ocxElement);	
		return ocxElement;
	}
	catch(err)
	{		
		Milan.commonutils.createDelayNotifyModel('提示', "印章对象装载错误!请确认您正确安装了NTKO安全电子印章系统！"+ err.number + ":" + err.description);			
		if(ocxElement)
		{
			ocxElement.removeNode();
		}
	}
	return null;
}
//注意：以下函数除提示信息之外，其他语句不要修改。
function NtkoReserved_RunSignHelper(ocxElement,UserName,FileName,PromptSelect,
		PrintMode,IsUseCertificate,IsLocked,IsCheckDocChange,
		IsShowUI,SignPass,SignType,IsAddComment,AdjustToHeight,SignIndex)
{
	if("object" != typeof(ocxElement)) return;
	ocxElement.SetUser(UserName);
	switch(SignType)
	{
		case 0:
			{
				try
				{
					ocxElement.DoSign(FileName,PromptSelect, SignPass, PrintMode, 
						IsUseCertificate, IsLocked,IsCheckDocChange,IsShowUI,IsAddComment);
				}
				catch(err)
				{		
					alert("加盖印章错误!");			
					ocxElement.Close();
					ocxElement.removeNode();
				}
			}
			break;
		case 1:
			{
				try
				{
					ocxElement.DoHandSign(PrintMode,IsUseCertificate,IsLocked,IsCheckDocChange,
						IsShowUI,SignPass,IsAddComment,AdjustToHeight);
				}
				catch(err)
				{
					alert("手写签名错误!");
					ocxElement.Close();
					ocxElement.removeNode();
				}		
			}	
			break;
		case 2:
			{
				try
				{
					ocxElement.DoSignFromEkey(SignPass,PrintMode,IsUseCertificate,IsLocked,
						IsCheckDocChange,IsShowUI,SignIndex,IsAddComment);
				}
				catch(err)
				{
					Milan.commonutils.createDelayNotifyModel('提示', "盖章操作已取消!");
					ocxElement.Close();
					ocxElement.removeNode();
				}		
			}	
			break;	
		case 3:
			{
				try
				{
					ocxElement.DoKeyBoardComment(PrintMode,IsUseCertificate,IsLocked,IsCheckDocChange,IsShowUI,SignPass);
				}
				catch(err)
				{
					alert("添加安全键盘批注错误!");
					ocxElement.Close();
					ocxElement.removeNode();
				}		
			}	
			break;				
		default: 
			{
				try
				{
					ocxElement.DoSign(FileName,true, SignPass, PrintMode, 
						IsUseCertificate, IsLocked,IsCheckDocChange,IsShowUI);
				}
				catch(err)
				{
					alert("加盖印章错误!");
					ocxElement.Close();
					ocxElement.removeNode();
				}					
			}
			break;	
	}
}